package com.example.ymm.modules1.service.impl.hl.kq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.sys.SysApprovalSetting;
import com.example.ymm.modules1.entity.my.sys.SysApprovalSettingLine;
import com.example.ymm.modules1.entity.my.sys.SysApprovalSettingNode;
import com.example.ymm.modules1.entity.my.user.*;
import com.example.ymm.modules1.mapper.my.user.KqDakaLogMapper;
import com.example.ymm.modules1.query.kq.*;
import com.example.ymm.modules1.service.dd.DingdingCheckService;
import com.example.ymm.modules1.service.dd.ms.DingNoticeService;
import com.example.ymm.modules1.service.dto.heng.ApprovalCreateViewDto;
import com.example.ymm.modules1.service.dto.heng.kq.ViewApproveDakaLog;
import com.example.ymm.modules1.service.dto.heng.kq.ViewKqDakaLog;
import com.example.ymm.modules1.service.dto.heng.kq.ViewKqRule;
import com.example.ymm.modules1.service.hl.kq.*;
import com.example.ymm.modules1.service.sys.SysApprovalSettingService;
import com.example.ymm.modules1.service.user.DbApprovalLogService;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@DSTransactional
@DS("slave2")
@Slf4j
public class KqDakaLogServiceImpl extends BaseServiceImpl<KqDakaLogMapper, KqDakaLog> implements KqDakaLogService {

    @Value("${spring.profiles.active}")
    String PD_MATCH;

    @Autowired
    DingdingCheckService dingdingCheckService;

    @Autowired
    KqUserService kqUserService;
    @Autowired
    KqGroupRuleService kqGroupRuleService;

    @Autowired
    KqDeptService kqDeptService;

    @Autowired
    SysApprovalSettingService sysApprovalSettingService;

    @Autowired
    DbApprovalLogService dbApprovalLogService;

    @Autowired
    DingNoticeService dingNoticeService;
    @Autowired
    KqApproveLogService kqApproveLogService;
    @Autowired
    KqDayLogService kqDayLogService;


    //手机端
    @Override
    public TableList<ViewKqDakaLog> list(KqDakaLogQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
        List<ViewKqDakaLog> arrs = phoneDakaList(criteria);
        PageInfo<ViewKqDakaLog> pageInfo = new PageInfo<>(arrs);
        TableList<ViewKqDakaLog> tableList = new TableList(pageInfo);
        return tableList;
    }

    @Override
    public TableList<ViewKqDakaLog> pcList(KqDakaLogQueryCriteria criteria, YmPageDto ymPage) {
        getPage(ymPage);
        List<ViewKqDakaLog> arrs = pcDakaList(criteria);
        PageInfo<ViewKqDakaLog> pageInfo = new PageInfo<>(arrs);
        TableList<ViewKqDakaLog> tableList = new TableList(pageInfo);
        return tableList;
    }

    @Override
    public TableList<ViewKqDakaLog> approvalTableList(KqApproveLogQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
        KqDakaLogQueryCriteria c2 = new KqDakaLogQueryCriteria();
        c2.setApproveNo(criteria.getApproveNo());
        List<ViewKqDakaLog> arrs = phoneDakaList(c2);
        PageInfo<ViewKqDakaLog> pageInfo = new PageInfo<>(arrs);
        TableList<ViewKqDakaLog> tableList = new TableList(pageInfo);
        return tableList;
    }

    public List<KqDakaLog> queryAll(KqDakaLogQueryCriteria criteria) {
        List<KqDakaLog> result = baseMapper.selectList(QueryHelpPlus.getPredicate(KqDakaLog.class, criteria));
        return result;
    }


    @Override
    public List<ViewKqDakaLog> phoneDakaList(KqDakaLogQueryCriteria criteria) {
        if (UtilValidate.isNotEmpty(criteria.getAddDate())) {
            criteria.setAddDateTime(DateKit.dateFormat(criteria.getAddDate() + " 00:00:00"));
        }
        List<ViewKqDakaLog> arrs = baseMapper.phoneDakaList(criteria);
        operateSetDakaTime(arrs, criteria);

        return arrs;
    }


    @Override
    public List<ViewKqDakaLog> pcDakaList(KqDakaLogQueryCriteria criteria) {
        if (UtilValidate.isNotEmpty(criteria.getAddDate())) {
            criteria.setAddDateTime(DateKit.dateFormat(criteria.getAddDate() + " 00:00:00"));
        }
        List<ViewKqDakaLog> arrs = baseMapper.pcDakaList(criteria);
        operateSetDakaTime(arrs, criteria);

        return arrs;
    }

    @Override
    public List<ViewKqDakaLog> lackUserDakas(KqDakaLogQueryCriteria criteria) {
        if (UtilValidate.isEmpty(criteria.getAddDate())) {
            throw new YmException("非法参数!");
        }
        List<ViewKqDakaLog> viewKqDakaLogs = phoneDakaList(criteria);
        List<ViewKqDakaLog> result = new ArrayList<>();
//        for (ViewKqDakaLog dakaLog: viewKqDakaLogs){
//            if(UtilValidate.isNotEmpty(dakaLog.getDdTimes())){
//                List<String> keys=new ArrayList<>();
//                if(UtilValidate.isEmpty(dakaLog.getShangwuUpTxt())&&UtilValidate.isEmpty(dakaLog.getShangwuUpTxt1())){
//                    //上午 上班缺卡
//                    keys.add("shangwuUpTxt");
//                }
//                if(UtilValidate.isEmpty(dakaLog.getShangwuDownTxt())&&UtilValidate.isEmpty(dakaLog.getShangwuDownTxt1())){
//                    //上午 下班缺卡
//                    keys.add("shangwuDownTxt");
//                }
//                if(UtilValidate.isEmpty(dakaLog.getXiawuUpTxt())&&UtilValidate.isEmpty(dakaLog.getXiawuUpTxt1())){
//                    //下午 上班缺卡
//                    keys.add("xiawuUpTxt");
//                }
//                if(UtilValidate.isEmpty(dakaLog.getXiawuDownTxt())&&UtilValidate.isEmpty(dakaLog.getXiawuDownTxt1())){
//                    //下午 下班缺卡
//                    keys.add("xiawuDownTxt");
//                }
//                if(UtilValidate.isNotEmpty(keys)){
//                    JSONObject xtShiJianObj=new JSONObject();
//                    xtShiJianObj.put("quekaList",keys);
//                    dakaLog.setXtShiJianObj(xtShiJianObj);
//                    result.add(dakaLog);
//                }
//            }
//
//        }
        return result;
    }

    /**
     * 系统计算打卡时间
     *
     * @param arrs
     */
    public void operateSetDakaTime(List<ViewKqDakaLog> arrs, KqDakaLogQueryCriteria criteria) {
        List<ViewKqRule> ruleGroupList = null;
        Map<String, String> deptIdMap = new HashMap<>();
        Map<String, List<ViewKqRule>> deptRuleMap = new HashMap<>();//deptId
        Map<String, Map<Integer, Integer>> deptRuleNumMap = new HashMap<>();//部门规则计数器 addDate:deptId
        if (UtilValidate.isNotEmpty(arrs)) {
            List<String> deptIdIn = new ArrayList<>();
            for (ViewKqDakaLog kqDakaLog : arrs) {
                deptIdMap.put(kqDakaLog.getKqGroupId(), kqDakaLog.getKqGroupId());
            }
            deptIdMap.entrySet().stream().forEach(entry -> {
                String deptId = entry.getKey();
                deptIdIn.add(deptId);
            });

            KqGroupRuleQueryCriteria c2 = new KqGroupRuleQueryCriteria();
            c2.setDeptIdIn(deptIdIn);
            ruleGroupList = kqGroupRuleService.getRuleGroupList(c2);
            Set<Map.Entry<String, String>> entries = deptIdMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String deptId = entry.getKey();
                List<ViewKqRule> rules = new ArrayList<>();
                for (ViewKqRule rule : ruleGroupList) {
                    if (rule.getDeptId().equals(deptId)) {
                        rules.add(rule);
                    }
                }
                if (UtilValidate.isNotEmpty(rules)) {
                    deptRuleMap.put(deptId, rules);
                }
            }
        }
        for (ViewKqDakaLog kqDakaLog : arrs) {
            if (UtilValidate.isNotEmpty(kqDakaLog.getDdTimes())) {
                String[] time_arr = kqDakaLog.getDdTimes().split(",");
                List<ViewKqRule> kqRules = new ArrayList<>();
                if (deptRuleMap.size() > 0) {
                    kqRules = deptRuleMap.get(kqDakaLog.getKqGroupId());
                }
                if (UtilValidate.isEmpty(kqRules)) {
                    kqRules = ruleGroupList;
                }
                // List<ViewKqRule> kqRules = deptRuleMap.get(kqDakaLog.getKqGroupId());
                //匹配考勤规则
                ViewKqRule kqRule = getDakaRule(kqDakaLog, time_arr, kqRules);
                String add_date = DateKit.dateFormat(kqDakaLog.getAddDate()).split(" ")[0];
                String key = add_date + ":" + kqDakaLog.getKqGroupId();
                if (UtilValidate.isEmpty(kqRule)) {
                    System.out.println(kqRule);
                }
                if (deptRuleNumMap.containsKey(key)) {
                    Map<Integer, Integer> map = deptRuleNumMap.get(key);
                    if (map.containsKey(kqRule.getType())) {
                        map.put(kqRule.getType(), map.get(kqRule.getType()) + 1);
                    } else {
                        map.put(kqRule.getType(), 1);
                    }
                    deptRuleNumMap.put(key, map);
                } else {
                    HashMap<Integer, Integer> map = new HashMap<>();
                    map.put(kqRule.getType(), 1);
                    deptRuleNumMap.put(key, map);
                }
            }

        }
        for (ViewKqDakaLog kqDakaLog : arrs) {

            //匹配规则数据
            String add_date = DateKit.dateFormat(kqDakaLog.getAddDate()).split(" ")[0];
            String key = add_date + ":" + kqDakaLog.getKqGroupId();

            List<ViewKqRule> kqRules = deptRuleMap.get(kqDakaLog.getKqGroupId());
            Map<Integer, Integer> integerIntegerMap = deptRuleNumMap.get(key);

            ViewKqRule kqRule = null;
//            if(UtilValidate.isNotEmpty(kqRules)&&UtilValidate.isNotEmpty(integerIntegerMap)){
//                Integer maxKey = null;
//                Integer maxValue = Integer.MIN_VALUE; // 初始化最大值为最小整数
//
//                // 遍历Map中的每个条目
//                for (Map.Entry<Integer, Integer> entry : integerIntegerMap.entrySet()) {
//                    Integer currentValue = entry.getValue();
//                    // 如果当前值大于已记录的最大值，则更新最大值和对应的键
//                    if (currentValue > maxValue) {
//                        maxValue = currentValue;
//                        maxKey = entry.getKey();
//                    }
//                }
//                for(ViewKqRule rule:kqRules){
//                    if(rule.getType().equals(maxKey)){
//                        kqRule=rule;//获取 最多人的考勤规则 大数据匹配
//                        break;
//                    }
//                }
//
//            }else{
//                //查找正常班
//                //正常班
//                for(ViewKqRule kqRule2 : ruleGroupList){
//                    if(kqRule2.getType().equals(1)){
//                        kqRule=kqRule2;
//                        break;
//                    }
//                }
//            }

            //最后还是找不到规则的情况
            if (UtilValidate.isEmpty(kqRule)) {
                if (UtilValidate.isNotEmpty(kqDakaLog.getKqRule())) {
                    kqRule = (ViewKqRule) kqDakaLog.getKqRule();
                } else {
                    //查找正常班
                    //正常班
                    for (ViewKqRule kqRule2 : kqRules) {
                        if (kqRule2.getType().equals(1)) {
                            kqRule = kqRule2;
                            break;
                        }
                    }
                }
            }
            kqDakaLog.setKqRule(kqRule);

            if (UtilValidate.isNotEmpty(kqDakaLog.getDdTimes())) {

                //匹配时间
                String[] time_arr = kqDakaLog.getDdTimes().split(",");

                operatorTime(kqDakaLog, time_arr, kqRule);
            }
            //标记审批状态
            setItemApproveName(kqDakaLog, criteria);
        }


    }


    @Override
    public List<ViewKqDakaLog> approvalDakaList(KqApproveLogQueryCriteria criteria) {
        List<ViewKqDakaLog> arrs = baseMapper.approvalDakaList(criteria);
        operateSetDakaTime(arrs, null);
        return arrs;
    }

    public void operatorTime(ViewKqDakaLog kqDakaLog, String[] time_arr, ViewKqRule kqRule) {
        if (UtilValidate.isNotEmpty(kqDakaLog.getIzJiaBan())) {
            kqDakaLog.setIzJiaBan1(kqDakaLog.getIzJiaBan() == 1 ? true : false);
        }
        /**
         * 1 判断 是正常班还是连班
         */
        //   ViewKqRule kqRule= getDakaRule(kqDakaLog,time_arr,ruleGroupList);
        /**
         * 2 匹配 6个时间点
         */
        setDaKaTime(kqDakaLog, time_arr, kqRule);

        /**
         * 3 计算全天时长
         */

        countQuantianShiChange(kqDakaLog);
    }


    /**
     * 标记审批状态
     */
    public void setItemApproveName(ViewKqDakaLog kqDakaLog, KqDakaLogQueryCriteria criteria) {
        int biao_zhun_type = 1;//标准时间类型 1 全天上班 0休息 2 上午半天 3下午半天
        BigDecimal biao_zhun_time = BigDecimal.ZERO;//标准上班时间
        BigDecimal result = BigDecimal.ZERO;
        String add_date = null;
        if (UtilValidate.isNotEmpty(kqDakaLog.getAddDate())) {
            add_date = DateKit.dateFormat(kqDakaLog.getAddDate()).split(" ")[0];
        } else {
            add_date = criteria.getAddDate();
        }
        String txt = null;
        List<String> txtArr = new ArrayList<>();
        String color = null;
        //设置审批进度
        if (UtilValidate.isNotEmpty(kqDakaLog.getKqApproveId())) {

            String editName = "";
            if (UtilValidate.isNotEmpty(kqDakaLog.getEditType())) {
                switch (kqDakaLog.getEditType()) {
                    case 0:
                        editName = "休息";
                        if(UtilValidate.isNotEmpty(kqDakaLog.getXiuxiType())){
                            switch (kqDakaLog.getXiuxiType()) {//休息类型：0全天 1 上午 2 下午
                                case 0:
                                    biao_zhun_type = 0;
                                    editName = "全天休息";
                                    break;
                                case 1:
                                    biao_zhun_type = 2;
                                    editName = "上午休息";
                                    break;
                                case 2:
                                    biao_zhun_type = 3;
                                    editName = "下午休息";
                                    break;
                            }
                        }

                        break;
                    case 1:
                        editName = "修改为" + kqDakaLog.getXtQuantianShichang1() + "小时";
                        break;
                }
            }

            if (UtilValidate.isNotEmpty(kqDakaLog.getKqApproveStatus())) {
                //审批状态：0未审批 1审批进行中 2审批通过 90审批拒绝
                String v = null;
                switch (kqDakaLog.getKqApproveStatus()) {
                    case 0:
                        v = "未审批";
                        color = "warning";
                        break;
                    case 1:
                        v = "审批中";
                        color = "warning";
                        break;
                    case 2:
                        v = "审批通过";
                        color = "success";
                        break;
                    case 90:
                        v = "审批拒绝";
                        color = "error";
                        break;
                }
                if (UtilValidate.isNotEmpty(editName)) {
                    txtArr.add(editName);
                }
                txtArr.add(v);
                if (UtilValidate.isNotEmpty(kqDakaLog.getXtQuantianShichang1())) {
                    txtArr.add(kqDakaLog.getXtQuantianShichang1().doubleValue() + "小时");
                }
                // txt=editName+","+v;
            } else {
                color = "warning";
                if (UtilValidate.isNotEmpty(editName)) {
                    txtArr.add(editName);
                }
                txtArr.add("未发起审批");
                if (UtilValidate.isNotEmpty(kqDakaLog.getXtQuantianShichang1())) {
                    txtArr.add(kqDakaLog.getXtQuantianShichang1().doubleValue() + "小时");
                }

            }

        } else {


            if (UtilValidate.isNotEmpty(kqDakaLog.getXtQuantianShichang1())
                    && kqDakaLog.getXtQuantianShichang1().compareTo(kqDakaLog.getXtQuantianShichang()) > 0) {
                color = "warning";
                txtArr.add("未审批");
                txtArr.add(kqDakaLog.getXtQuantianShichang1().doubleValue() + "小时");
            }
        }

        if(UtilValidate.isEmpty(kqDakaLog.getDakaId())){
            color = "warning";
            txtArr.add("未打卡");
        }

        if (UtilValidate.isNotEmpty(txtArr)) {
            txt = String.join(",", txtArr);
            kqDakaLog.setKqApproveStatusColor(color);
            kqDakaLog.setKqApproveStatusValue(txt);
        }


        if (UtilValidate.isNotEmpty(kqDakaLog.getXtShiJianJson())) {
            JSONObject xtShiJianJson = JSONObject.parseObject(kqDakaLog.getXtShiJianJson());
            kqDakaLog.setXtShiJianObj(xtShiJianJson);
            if (xtShiJianJson.containsKey("考勤结果")) {
                String jiaQin = xtShiJianJson.getString("考勤结果");
                String jiaqi = "陪产假,产假,事假,丧假,休息";
                String[] jia_arr = jiaqi.split(",");
                String jiaQinResult = null, yiChangTxt = null;
                for (String jia_jian : jia_arr) {
                    if (jiaQin.contains(jia_jian)) {
                        jiaQinResult = jia_jian;
                        biao_zhun_type = 0;
                        break;
                    }
                }
                kqDakaLog.setJiaQingTxt(jiaQinResult);

                String yichan = "旷工";//,迟到,早退
                String[] yi_arr = yichan.split(",");
                for (String s : yi_arr) {
                    if (jiaQin.contains(s)) {
                        yiChangTxt = s;
                        break;
                    }
                }
                kqDakaLog.setYiChangTxt(yiChangTxt);
            }
        }

        //计算标准时间
        if (biao_zhun_type > 0) {

            double v1 = 0d, v2 = 0d, v3 = 0d;//系统判定
            KqRule kqRule = kqDakaLog.getKqRule();

            String shangwuUpTxt = kqRule.getShangwuUpTxt(), shangwuDownTxt = kqRule.getShangwuDownTxt(),
                    xiawuUpTxt = kqRule.getXiawuUpTxt(), xiawuDownTxt = kqRule.getXiawuDownTxt(),
                    wanshangUpTxt = kqRule.getWanshangUpTxt(), wanshangDownTxt = kqRule.getWanshangDownTxt();

            if (UtilValidate.isNotEmpty(shangwuUpTxt) && UtilValidate.isNotEmpty(shangwuDownTxt)) {

                String s1 = add_date + " " + shangwuUpTxt + ":00";
                String s2 = add_date + " " + shangwuDownTxt + ":00";
                v1 = DateKit.timeDifference(s1, s2);
            }

            if (UtilValidate.isNotEmpty(xiawuUpTxt) && UtilValidate.isNotEmpty(xiawuDownTxt)) {
                String s1 = add_date + " " + xiawuUpTxt + ":00";
                String s2 = add_date + " " + xiawuDownTxt + ":00";
                v2 = DateKit.timeDifference(s1, s2);
            }
            if (UtilValidate.isNotEmpty(wanshangUpTxt) && UtilValidate.isNotEmpty(wanshangDownTxt)) {
                String s1 = add_date + " " + wanshangUpTxt + ":00";
                String s2 = add_date + " " + wanshangDownTxt + ":00";
                v3 = DateKit.timeDifference(s1, s2);
            }


            BigDecimal shangwu = new BigDecimal(v1).subtract(new BigDecimal(0.1));
            BigDecimal xiawu = new BigDecimal(v2).subtract(new BigDecimal(0.1));
            // BigDecimal washang=new BigDecimal(v3);
            switch (biao_zhun_type) {
                case 1:
                    biao_zhun_time = shangwu.add(xiawu).setScale(2, BigDecimal.ROUND_HALF_UP);
                    break;
                case 2:
                    biao_zhun_time = xiawu;
                    break;
                case 3:
                    break;
            }


            if (biao_zhun_time.doubleValue() > 0) {
                String v = biao_zhun_time.doubleValue() + "";

                //截取小数部分
                String[] split = v.split("\\.");

                BigDecimal o2 = new BigDecimal(0.2);
                BigDecimal o5 = new BigDecimal(0.5);
                BigDecimal b1 = new BigDecimal(split[0]);
                BigDecimal b2 = new BigDecimal("0." + split[1]);
                if (b2.compareTo(o5) >= 0) {
                    result = b1.add(BigDecimal.ONE);
                } else if (b2.compareTo(o2) >= 0 && b2.compareTo(o5) < 0) {
                    result = b1.add(o5);
                } else {
                    result = b1;
                }
            }

        }


        if (UtilValidate.isEmpty(kqDakaLog.getKqApproveId())
                && UtilValidate.isEmpty(kqDakaLog.getId())
                && UtilValidate.isEmpty(kqDakaLog.getJiaQingTxt())
                && UtilValidate.isEmpty(kqDakaLog.getYiChangTxt())
        ) {
            //未来的时间
            kqDakaLog.setKqApproveStatusColor("warning");
            kqDakaLog.setKqApproveStatusValue("未打卡");
            result = BigDecimal.ZERO;
        }


        kqDakaLog.setBiaoZhunTime(result);
        kqDakaLog.setBiaoZhunType(biao_zhun_type);


    }

    //匹配考勤规则
    public ViewKqRule getDakaRule(ViewKqDakaLog kqDakaLog, String[] time_arr, List<ViewKqRule> ruleGroupList) {

        ViewKqRule kqRule = null;
        String add_date = DateKit.dateFormat(kqDakaLog.getAddDate()).split(" ")[0];
        String last_time = time_arr[time_arr.length - 1];//最后一个时间点
        Date last_date = DateKit.dateFormat(add_date + " " + last_time);

        //oem
        if (UtilValidate.isNotEmpty(kqDakaLog.getIzLianBan())) {
            //连班
            if (kqDakaLog.getIzLianBan().equals(1)) {
                for (ViewKqRule kqRule2 : ruleGroupList) {
                    if (kqRule2.getType().equals(2)) {
                        kqRule = kqRule2;
                        break;
                    }
                }
            } else if (kqDakaLog.getIzLianBan().equals(0)) {
                //正常班
                for (ViewKqRule kqRule2 : ruleGroupList) {
                    if (kqRule2.getType().equals(1)) {
                        kqRule = kqRule2;
                        break;
                    }
                }
            }
        } else {
            //非oem

            /**
             * 是否是DKL，表壳厂 车间的人
             * ||kqDakaLog.getGroupName().contains("表壳厂")
             */
            if (kqDakaLog.getGroupName().contains("DKL")) {

                /**
                 * 判断是否连班
                 */
                /**
                 * 1 判断最后一个打卡时间是否超过18:00
                 * 2 判断 17：00 -19：00中间有没有打卡
                 *
                 */
                Date t13 = DateKit.dateFormat(add_date + " 17:00:00");
                Date t18 = DateKit.dateFormat(add_date + " 18:00:00");
                boolean con1 = last_date.after(t18);
                if (con1) {
                    boolean con2 = false;
                    for (String time : time_arr) {
                        Date date = DateKit.dateFormat(add_date + " " + time);
                        if (date.after(t13) && date.before(t18)) {
                            con2 = true;
                            break;
                        }
                    }
                    if (con1 && !con2) {
                        //连班
                        for (ViewKqRule kqRule2 : ruleGroupList) {
                            if (kqRule2.getType().equals(2)) {
                                kqRule = kqRule2;
                                break;
                            }
                        }
                    } else {
                        //加班
                        for (ViewKqRule kqRule2 : ruleGroupList) {
                            if (kqRule2.getType().equals(3)) {
                                kqRule = kqRule2;
                                break;
                            }
                        }
                    }
                } else {
                    //正常班
                    for (ViewKqRule kqRule2 : ruleGroupList) {
                        if (kqRule2.getType().equals(1)) {
                            kqRule = kqRule2;
                            break;
                        }
                    }
                }

            } else {
                //剩余其他部门

                //1 判断规则中有没有连班

                boolean lian_ban = false;
                for (ViewKqRule kqRule2 : ruleGroupList) {
                    if (kqRule2.getType().equals(2)) {
                        lian_ban = true;
                    }
                }
                //匹配是否连班
                if (lian_ban) {
                    /**
                     * 1 判断最后一个打卡时间是否超过18:00
                     * 2 判断 17：00 -19：00中间有没有打卡
                     *
                     */
                    Date t13 = DateKit.dateFormat(add_date + " 17:00:00");
                    Date t18 = DateKit.dateFormat(add_date + " 18:00:00");
                    boolean con1 = last_date.after(t18);
                    if (con1) {
                        boolean con2 = false;
                        for (String time : time_arr) {
                            Date date = DateKit.dateFormat(add_date + " " + time);
                            if (date.after(t13) && date.before(t18)) {
                                con2 = true;
                                break;
                            }
                        }
                        if (con1 && !con2) {
                            //连班
                            for (ViewKqRule kqRule2 : ruleGroupList) {
                                if (kqRule2.getType().equals(2)) {
                                    kqRule = kqRule2;
                                    break;
                                }
                            }
                        }
                    }
                } else {

                    //其他没有连班规则的车间
                    for (ViewKqRule kqRule2 : ruleGroupList) {
                        //晚上上班 晚上最后一个时间点，大于晚上加班 上班时间 就能判断 晚上有上班
                        if (UtilValidate.isNotEmpty(kqRule2.getWanshangUpTxt())) {
                            Date wanshangUp_date = DateKit.dateFormat(add_date + " " + kqRule2.getWanshangUpTxt() + ":00");
                            if (last_date.after(wanshangUp_date)) {
                                //晚上有加班
                                kqRule = kqRule2;
                                break;
                            }
                        }
                    }
                }

                //没加班就按正常班
                if (kqRule == null) {
                    //正常班
                    for (ViewKqRule kqRule2 : ruleGroupList) {
                        if (kqRule2.getType().equals(1)) {
                            kqRule = kqRule2;
                            break;
                        }
                    }
                }
            }


        }

        /**
         * 系统猜测 有没有加班
         */
        if (UtilValidate.isEmpty(kqDakaLog.getIzJiaBan())) {
            Date wanshangUp_date = DateKit.dateFormat(add_date + " " + "18:30:00");
            if (last_date.after(wanshangUp_date)) {
                //晚上有加班
                kqDakaLog.setIzJiaBan1(true);
            }
        }

        kqDakaLog.setKqRule(kqRule);
        return kqRule;
    }

    /**
     * 2 匹配 6个时间点
     */
    public void setDaKaTime(ViewKqDakaLog kqDakaLog, String[] time_arr, ViewKqRule kqRule) {
        String add_date = DateKit.dateFormat(kqDakaLog.getAddDate()).split(" ")[0];
        Map<String, String> time_map = new HashMap<>();//已使用的 用户打卡时间，不可重复计算
        /**
         * a 匹配相近时间
         */

        for (String time : time_arr) {
            Date date = DateKit.dateFormat(add_date + " " + time);
            Date s_w_up = DateKit.dateFormat(add_date + " " + kqRule.getShangwuUpTxt() + ":00");
            Date s_w_down = DateKit.dateFormat(add_date + " " + kqRule.getShangwuDownTxt() + ":00");
            if (UtilValidate.isEmpty(time_map.get(time))) {
                /**
                 * 上午上班
                 */
                if (DateKit.isWithin30Minutes(date, s_w_up)) {
                    if (date.getTime() < s_w_up.getTime()) {
                        //早来
                        kqDakaLog.setShangwuUpTxt(kqRule.getShangwuUpTxt() + ":00");
                        time_map.put(time, time);
                        continue;
                    } else {
                        //晚来
                        kqDakaLog.setShangwuUpTxt(time);
                        time_map.put(time, time);
                        continue;
                    }
                }
                /**
                 * 上午下班
                 */
                //匹配上午下班

                if (DateKit.isWithin30Minutes(date, s_w_down)) {
                    if (date.getTime() < s_w_down.getTime()) {
                        //早走
                        kqDakaLog.setShangwuDownTxt(time);
                        time_map.put(time, time);
                        continue;
                    } else {
                        //晚走
                        kqDakaLog.setShangwuDownTxt(kqRule.getShangwuDownTxt() + ":00");
                        time_map.put(time, time);
                        continue;
                    }
                }
                /**
                 * 下午上班
                 */
                //中午-下午上班-早来
                Date x_w_up = DateKit.dateFormat(add_date + " " + kqRule.getXiawuUpTxt() + ":00");//下午上班时间
                Date x_w_down = DateKit.dateFormat(add_date + " " + kqRule.getXiawuDownTxt() + ":00");//下午下班时间

                //匹配 下午上班
                if (DateKit.isWithin30Minutes(date, x_w_up) && UtilValidate.isEmpty(kqDakaLog.getXiawuUpTxt())) {

                    if (date.getTime() > x_w_up.getTime()) {
                        kqDakaLog.setXiawuUpTxt(time);
                        time_map.put(time, time);
                        continue;
                    } else {
                        kqDakaLog.setXiawuUpTxt(kqRule.getXiawuUpTxt() + ":00");
                        time_map.put(time, time);
                        continue;
                    }

                }

                /**
                 * 下午下班
                 */
                Date w_s_up_date = null;
                //匹配 下午下班
                if (DateKit.isWithin30Minutes(date, x_w_down) && UtilValidate.isEmpty(kqDakaLog.getXiawuDownTxt())) {
                    if (date.getTime() < x_w_down.getTime()) {
                        kqDakaLog.setXiawuDownTxt(time);//早走
                        time_map.put(time, time);
                        continue;
                    } else {
                        //晚走
                        kqDakaLog.setXiawuDownTxt(kqRule.getXiawuDownTxt() + ":00");
                        time_map.put(time, time);
                        continue;
                    }
                }

                /**
                 * 晚上上班
                 */
                if (UtilValidate.isNotEmpty(kqRule.getWanshangUpTxt()) && UtilValidate.isEmpty(kqDakaLog.getWanshangUpTxt())) {
                    w_s_up_date = DateKit.dateFormat(add_date + " " + kqRule.getWanshangUpTxt() + ":00");

                    //匹配晚上 上班
                    if (DateKit.isWithin30Minutes(date, w_s_up_date)) {
                        if (date.getTime() < w_s_up_date.getTime()) {
                            kqDakaLog.setWanshangUpTxt(kqRule.getWanshangUpTxt() + ":00");//早来
                            time_map.put(time, time);
                            continue;
                        } else {
                            //晚来
                            kqDakaLog.setWanshangUpTxt(time);
                            time_map.put(time, time);
                            continue;
                        }
                    }
                }

            }
        }

        /**
         * b 计算剩余不相近时间
         */
        for (String time : time_arr) {
            Date date = DateKit.dateFormat(add_date + " " + time);
            Date s_w_up = DateKit.dateFormat(add_date + " " + kqRule.getShangwuUpTxt() + ":00");
            Date s_w_down = DateKit.dateFormat(add_date + " " + kqRule.getShangwuDownTxt() + ":00");

            /**
             * 上午上班
             */
            if (UtilValidate.isEmpty(time_map.get(time))) {

                if (UtilValidate.isEmpty(kqDakaLog.getShangwuUpTxt())) {
                    if (date.before(s_w_up)) {
                        //上午上班前打卡
                        kqDakaLog.setShangwuUpTxt(kqRule.getShangwuUpTxt() + ":00");
                        time_map.put(time, time);
                        continue;
                    } else {
                        if (date.getTime() > s_w_up.getTime() && date.getTime() < s_w_down.getTime()) {
                            kqDakaLog.setShangwuUpTxt(time);
                            time_map.put(time, time);
                            continue;
                        }
                    }
                }

                Date zhong_wu_limit = DateKit.dateFormat(add_date + " " + kqRule.getZhongwuLimitTxt() + ":00");
                Date xia_wu_limit = DateKit.dateFormat(add_date + " " + kqRule.getXiawuLimitTxt() + ":00");

                /**
                 * 上午下班
                 */

                if (UtilValidate.isEmpty(kqDakaLog.getShangwuDownTxt())) {
                    //上午上班-上午下班 下班早走

                    if (date.getTime() > s_w_up.getTime() && date.getTime() < s_w_down.getTime()) {
                        kqDakaLog.setShangwuDownTxt(time);
                        time_map.put(time, time);
                        continue;
                    }
                    //上午上班-上午下班 下班晚走
                    if (date.getTime() > s_w_down.getTime() && date.getTime() < zhong_wu_limit.getTime()) {
                        kqDakaLog.setShangwuDownTxt(kqRule.getShangwuDownTxt() + ":00");
                        time_map.put(time, time);
                        continue;
                    }
                }

                /**
                 * 下午上班
                 */
                //中午-下午上班-早来
                Date x_w_up = DateKit.dateFormat(add_date + " " + kqRule.getXiawuUpTxt() + ":00");//下午上班时间
                Date x_w_down = DateKit.dateFormat(add_date + " " + kqRule.getXiawuDownTxt() + ":00");//下午下班时间

                //匹配 下午上班

                if (UtilValidate.isEmpty(kqDakaLog.getXiawuUpTxt())) {
                    if (date.getTime() > zhong_wu_limit.getTime() && date.getTime() < x_w_up.getTime()) {
                        kqDakaLog.setXiawuUpTxt(kqRule.getXiawuUpTxt() + ":00");
                        time_map.put(time, time);
                        continue;
                    } else if (date.getTime() > x_w_up.getTime() && date.getTime() < x_w_down.getTime()) {
                        //下午上班-下午下班  -晚来
                        kqDakaLog.setXiawuUpTxt(time);
                        time_map.put(time, time);
                        continue;
                    }
                }


                /**
                 * 下午下班
                 */
                Date w_s_up_date = null;

                if (UtilValidate.isEmpty(kqDakaLog.getXiawuDownTxt())) {
                    //正常班的 下午下班 -早走
                    if (date.getTime() > x_w_up.getTime() && date.getTime() < x_w_down.getTime()) {
                        kqDakaLog.setXiawuDownTxt(time);
                        time_map.put(time, time);
                        continue;
                    }
                    //下午下班-晚上上班  -晚走
                    if (date.getTime() > x_w_down.getTime() && date.getTime() < xia_wu_limit.getTime()) {
                        kqDakaLog.setXiawuDownTxt(kqRule.getXiawuDownTxt() + ":00");
                        time_map.put(time, time);
                        continue;
                    }
//                    else if(date.getTime()>x_w_down.getTime()){
//                        kqDakaLog.setXiawuDownTxt(kqRule.getXiawuDownTxt()+":00");
//                        time_map.put(time,time);
//                        continue;
//                    }
                }


                /**
                 * 晚上上班
                 */
                if (UtilValidate.isNotEmpty(kqRule.getWanshangUpTxt())) {
                    w_s_up_date = DateKit.dateFormat(add_date + " " + kqRule.getWanshangUpTxt() + ":00");


                    //晚上上班 -早来
                    if (UtilValidate.isEmpty(kqDakaLog.getWanshangUpTxt())) {

                        if (date.getTime() > xia_wu_limit.getTime() && date.getTime() < w_s_up_date.getTime()) {
                            kqDakaLog.setWanshangUpTxt(kqRule.getWanshangUpTxt() + ":00");
                            time_map.put(time, time);
                            continue;
                        } else if (date.getTime() > w_s_up_date.getTime()) {
                            //晚上上班 -晚来
                            kqDakaLog.setWanshangUpTxt(time);
                            time_map.put(time, time);
                            continue;
                        }
                    }


                    // 晚上下班
                    if (UtilValidate.isNotEmpty(kqRule.getWanshangDownTxt())) {
                        Date w_s_down_date = DateKit.dateFormat(add_date + " " + kqRule.getWanshangDownTxt() + ":00");
                        //晚上上班 -晚来
                        if (date.getTime() > w_s_up_date.getTime() && date.getTime() < w_s_down_date.getTime()) {
                            kqDakaLog.setWanshangDownTxt(time);
                            time_map.put(time, time);
                            continue;
                        }
                        //晚上下班 -早走
                        if (date.getTime() > w_s_up_date.getTime() && date.getTime() < w_s_down_date.getTime()) {
                            kqDakaLog.setWanshangDownTxt(time);
                            time_map.put(time, time);
                            continue;
                        }
                        //晚上下班 -晚走
                        if (date.getTime() > w_s_down_date.getTime()) {
                            kqDakaLog.setWanshangDownTxt(time);
                            time_map.put(time, time);
                            continue;
                        }
                    } else {
                        if (date.getTime() > w_s_up_date.getTime()) {
                            kqDakaLog.setWanshangDownTxt(time);
                            time_map.put(time, time);
                            continue;
                        }
                    }


                }
            }


        }
    }

    /**
     * 3 计算全天时长
     */
    public void countQuantianShiChange(ViewKqDakaLog kqDakaLog) {
        String add_date = DateKit.dateFormat(kqDakaLog.getAddDate()).split(" ")[0];

        /**
         * 上午
         */
        double v1 = 0d, v2 = 0d, v3 = 0d;//系统判定
        double v11 = 0d, v21 = 0d, v31 = 0d;//修改和审批状态

        boolean iz_edit = false;//是否有修改

        String shangwuUpTxt = kqDakaLog.getShangwuUpTxt(), shangwuDownTxt = kqDakaLog.getShangwuDownTxt(),
                xiawuUpTxt = kqDakaLog.getXiawuUpTxt(), xiawuDownTxt = kqDakaLog.getXiawuDownTxt(),
                wanshangUpTxt = kqDakaLog.getWanshangUpTxt(), wanshangDownTxt = kqDakaLog.getWanshangDownTxt();

        String shangwuUpTxt1 = kqDakaLog.getShangwuUpTxt(), shangwuDownTxt1 = kqDakaLog.getShangwuDownTxt(),
                xiawuUpTxt1 = kqDakaLog.getXiawuUpTxt(), xiawuDownTxt1 = kqDakaLog.getXiawuDownTxt(),
                wanshangUpTxt1 = kqDakaLog.getWanshangUpTxt(), wanshangDownTxt1 = kqDakaLog.getWanshangDownTxt();

        if (UtilValidate.isNotEmpty(kqDakaLog.getShangwuUpTxt1()) || UtilValidate.isNotEmpty(kqDakaLog.getShangwuDownTxt1()) ||
                UtilValidate.isNotEmpty(kqDakaLog.getXiawuUpTxt1()) || UtilValidate.isNotEmpty(kqDakaLog.getXiawuDownTxt1())
                || UtilValidate.isNotEmpty(kqDakaLog.getWanshangUpTxt1()) || UtilValidate.isNotEmpty(kqDakaLog.getWanshangDownTxt1())) {
            iz_edit = true;
        }

        if (UtilValidate.isNotEmpty(kqDakaLog.getShangwuUpTxt1())) {
            shangwuUpTxt1 = kqDakaLog.getShangwuUpTxt1();
        }
        if (UtilValidate.isNotEmpty(kqDakaLog.getShangwuDownTxt1())) {
            shangwuDownTxt1 = kqDakaLog.getShangwuDownTxt1();
        }
        if (UtilValidate.isNotEmpty(shangwuUpTxt) && UtilValidate.isNotEmpty(shangwuDownTxt)) {

            String s1 = add_date + " " + shangwuUpTxt;
            String s2 = add_date + " " + shangwuDownTxt;
            v1 = DateKit.timeDifference(s1, s2);
        }
        if (UtilValidate.isNotEmpty(shangwuUpTxt1) && UtilValidate.isNotEmpty(shangwuDownTxt1)) {

            String s1 = add_date + " " + shangwuUpTxt1;
            String s2 = add_date + " " + shangwuDownTxt1;
            v11 = DateKit.timeDifference(s1, s2);
        }
        /**
         * 下午
         */

        if (UtilValidate.isNotEmpty(kqDakaLog.getXiawuUpTxt1())) {
            xiawuUpTxt1 = kqDakaLog.getXiawuUpTxt1();

        }
        if (UtilValidate.isNotEmpty(kqDakaLog.getXiawuDownTxt1())) {
            xiawuDownTxt1 = kqDakaLog.getXiawuDownTxt1();
        }
        if (UtilValidate.isNotEmpty(xiawuUpTxt) && UtilValidate.isNotEmpty(xiawuDownTxt)) {
            String s1 = add_date + " " + xiawuUpTxt;
            String s2 = add_date + " " + xiawuDownTxt;
            v2 = DateKit.timeDifference(s1, s2);
        }
        if (UtilValidate.isNotEmpty(xiawuUpTxt1) && UtilValidate.isNotEmpty(xiawuDownTxt1)) {
            String s1 = add_date + " " + xiawuUpTxt1;
            String s2 = add_date + " " + xiawuDownTxt1;
            v21 = DateKit.timeDifference(s1, s2);
        }
        /**
         * 晚上
         */
        if (kqDakaLog.getIzJiaBan1() != null && kqDakaLog.getIzJiaBan1()) {
            if (UtilValidate.isNotEmpty(kqDakaLog.getWanshangUpTxt1())) {
                wanshangUpTxt1 = kqDakaLog.getWanshangUpTxt1();
            }
            if (UtilValidate.isNotEmpty(kqDakaLog.getWanshangDownTxt1())) {
                wanshangDownTxt1 = kqDakaLog.getWanshangDownTxt1();
            }
            if (UtilValidate.isNotEmpty(wanshangUpTxt) && UtilValidate.isNotEmpty(wanshangDownTxt)) {
                String s1 = add_date + " " + wanshangUpTxt;
                String s2 = add_date + " " + wanshangDownTxt;
                v3 = DateKit.timeDifference(s1, s2);
            }
            if (UtilValidate.isNotEmpty(wanshangUpTxt1) && UtilValidate.isNotEmpty(wanshangDownTxt1)) {
                String s1 = add_date + " " + wanshangUpTxt1;
                String s2 = add_date + " " + wanshangDownTxt1;
                v31 = DateKit.timeDifference(s1, s2);
            }
        }
        //这里扣减 20分钟=1/3 即0.33个小时

        /**
         * 计算系统判定时间
         */
        BigDecimal shangwu = new BigDecimal(v1).subtract(new BigDecimal(0.1));
        BigDecimal xiawu = new BigDecimal(v2).subtract(new BigDecimal(0.1));
        BigDecimal washang = new BigDecimal(v3);
        BigDecimal bigDecimal = shangwu.add(xiawu).add(washang).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal result = BigDecimal.ZERO;
        if (bigDecimal.doubleValue() > 0) {
            String v = bigDecimal.doubleValue() + "";

            //截取小数部分
            String[] split = v.split("\\.");

            BigDecimal o2 = new BigDecimal(0.2);
            BigDecimal o5 = new BigDecimal(0.5);
            BigDecimal b1 = new BigDecimal(split[0]);
            BigDecimal b2 = new BigDecimal("0." + split[1]);
            if (b2.compareTo(o5) >= 0) {
                result = b1.add(BigDecimal.ONE);
            } else if (b2.compareTo(o2) >= 0 && b2.compareTo(o5) < 0) {
                result = b1.add(o5);
            } else {
                result = b1;
            }
        }

        /**
         * 修改后的统计
         */
        BigDecimal bigDecimal1 = new BigDecimal(v11 + v21 + v31).subtract(new BigDecimal(0.2)).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal result1 = BigDecimal.ZERO;
        if (bigDecimal1.doubleValue() > 0) {
            String v = bigDecimal1.doubleValue() + "";

            //截取小数部分
            String[] split = v.split("\\.");

            BigDecimal o2 = new BigDecimal(0.2);
            BigDecimal o5 = new BigDecimal(0.5);
            BigDecimal b1 = new BigDecimal(split[0]);
            BigDecimal b2 = new BigDecimal("0." + split[1]);
            if (b2.compareTo(o5) >= 0) {
                result1 = b1.add(BigDecimal.ONE);
            } else if (b2.compareTo(o2) >= 0 && b2.compareTo(o5) < 0) {
                result1 = b1.add(o5);
            } else {
                result1 = b1;
            }
        }
        if (UtilValidate.isNotEmpty(kqDakaLog.getKqApproveStatus()) && kqDakaLog.getKqApproveStatus() == 2) {
            kqDakaLog.setXtQuantianShichang(result1);
        } else {
            kqDakaLog.setXtQuantianShichang(result);
        }
        kqDakaLog.setXtQuantianShichang1(result1);

    }


    @Override
    public ViewKqDakaLog detail(String id) {
        KqDakaLogQueryCriteria criteria = new KqDakaLogQueryCriteria();
        criteria.setId(id);
        List<ViewKqDakaLog> viewKqDakaLogs = phoneDakaList(criteria);
        if (viewKqDakaLogs.size() > 0) {
            return viewKqDakaLogs.get(0);
        }
        return null;
    }

    @Override
    public ViewKqDakaLog countDakaDetail(ViewKqDakaLog viewKqDakaLog) {
        countQuantianShiChange(viewKqDakaLog);
        setItemApproveName(viewKqDakaLog, null);
        return viewKqDakaLog;
    }

    @Override
    public void batchUpDakaLog(ViewApproveDakaLog approveDakaLog) {
        //TODO 废弃
        if (UtilValidate.isEmpty(approveDakaLog.getAddDateStr())) {
            throw new YmException("非法参数!");
        }
        KqDakaLogQueryCriteria criteria = new KqDakaLogQueryCriteria();
        String userName = getUserName();
        KqDept kqDept = kqDeptService.findByGroupUserName(userName);
        if (UtilValidate.isNotEmpty(kqDept)) {
            criteria.setGroupUserId(kqDept.getGroupUserId());
        }
        KqDept kqDept2 = kqDeptService.findByManageUserName(userName);
        if (UtilValidate.isNotEmpty(kqDept2)) {
            criteria.setManageUserId(kqDept2.getManageUserId());
        }
        if (UtilValidate.isEmpty(criteria.getGroupUserId()) && UtilValidate.isEmpty(criteria.getManageUserId())) {
            throw new YmException("您无车间权限!");
        }
        criteria.setAddDate(approveDakaLog.getAddDateStr());
        List<ViewKqDakaLog> viewKqDakaLogs = phoneDakaList(criteria);
//        List<ViewKqDakaLog> result = new ArrayList<>();
//        for (ViewKqDakaLog dakaLog: viewKqDakaLogs) {
//            if (UtilValidate.isNotEmpty(dakaLog.getDdTimes())) {
//                KqDakaLog u_dakaLog = new KqDakaLog();
//                u_dakaLog.setId(dakaLog.getId());
//                u_dakaLog.setShangwuUpTxt1(UtilValidate.isNotEmpty(approveDakaLog.getShangwuUpTxt1())?approveDakaLog.getShangwuUpTxt1():"");
//                u_dakaLog.setShangwuDownTxt1(UtilValidate.isNotEmpty(approveDakaLog.getShangwuDownTxt1())?approveDakaLog.getShangwuDownTxt1():"");
//                u_dakaLog.setXiawuUpTxt1(UtilValidate.isNotEmpty(approveDakaLog.getXiawuUpTxt1())?approveDakaLog.getXiawuUpTxt1():"");
//                u_dakaLog.setXiawuDownTxt1(UtilValidate.isNotEmpty(approveDakaLog.getXiawuDownTxt1())?approveDakaLog.getXiawuDownTxt1():"");
//                u_dakaLog.setWanshangUpTxt1(UtilValidate.isNotEmpty(approveDakaLog.getWanshangUpTxt1())?approveDakaLog.getWanshangUpTxt1():"");
//                u_dakaLog.setWanshangDownTxt1(UtilValidate.isNotEmpty(approveDakaLog.getWanshangDownTxt1())?approveDakaLog.getWanshangDownTxt1():"");
//                u_dakaLog.setRemark(approveDakaLog.getRemark());
//                if(UtilValidate.isNotEmpty(approveDakaLog.getIzJiaBan1())){
//                    u_dakaLog.setIzJiaBan(approveDakaLog.getIzJiaBan1()?1:0);
//                }else{
//                    u_dakaLog.setIzJiaBan(0);
//                }
//                u_dakaLog.setEditType(approveDakaLog.getEditType());
//                u_dakaLog.setXiuxiType(approveDakaLog.getXiuxiType());
//                updateById(u_dakaLog);
//            }
//        }
    }

    @Override
    public String saveDakaDetail(ViewKqDakaLog viewKqDakaLog) {
        KqDayLog dayLog = new KqDayLog();
        dayLog.setId(viewKqDakaLog.getId());

        String add_date = DateKit.dateFormat(viewKqDakaLog.getAddDate()).split(" ")[0];

        KqApproveLog approveLog = null;//kqApproveLogService.getUserIdAndAddDate(viewKqDakaLog.getUserId(), add_date)
        if (UtilValidate.isNotEmpty(viewKqDakaLog.getKqApproveId())) {
            approveLog = kqApproveLogService.getById(viewKqDakaLog.getKqApproveId());
        }
        if (UtilValidate.isEmpty(approveLog)) {
            approveLog = new KqApproveLog();
            approveLog.setAddDate(DateKit.dateFormat(add_date + " 00:00:00"));
            approveLog.setAddDateStr(add_date);
            approveLog.setUserId(viewKqDakaLog.getUserId());
            approveLog.setUserName(viewKqDakaLog.getUserName());
            approveLog.setDakaId(viewKqDakaLog.getId());
        }
        if (UtilValidate.isNotEmpty(viewKqDakaLog.getKqRule())) {
            approveLog.setKqRuleId(viewKqDakaLog.getKqRule().getId());
        }
        if (UtilValidate.isNotEmpty(viewKqDakaLog.getIzJiaBan1())) {
            approveLog.setIzJiaBan(viewKqDakaLog.getIzJiaBan1() ? 1 : 0);
        }
        approveLog.setEditType(viewKqDakaLog.getEditType());
        approveLog.setXiuxiType(viewKqDakaLog.getXiuxiType());
        approveLog.setRemark(viewKqDakaLog.getRemark());
        approveLog.setShangwuUpTxt1(viewKqDakaLog.getShangwuUpTxt1());
        approveLog.setShangwuDownTxt1(viewKqDakaLog.getShangwuDownTxt1());
        approveLog.setXiawuUpTxt1(viewKqDakaLog.getXiawuUpTxt1());
        approveLog.setXiawuDownTxt1(viewKqDakaLog.getXiawuDownTxt1());
        approveLog.setWanshangUpTxt1(viewKqDakaLog.getWanshangUpTxt1());
        approveLog.setWanshangDownTxt1(viewKqDakaLog.getWanshangDownTxt1());
        approveLog.setRemark(viewKqDakaLog.getRemark());
        kqApproveLogService.saveOrUpdate(approveLog);
        dayLog.setKqApproveId(approveLog.getId());
        kqDayLogService.updateById(dayLog);
        return approveLog.getId();
    }


    @Override
    public List<JSONObject> getUserXiuxiDetail(ViewKqDakaLog viewKqDakaLog) {
        List<JSONObject> list = new ArrayList<>();

        return list;
    }

    @Override
    public Integer userDakaCount(KqDakaLogQueryCriteria criteria) {
        return baseMapper.userDakaCount(criteria);
    }

    /**
     * 同步打卡数据
     *
     * @param criteria
     */
    @Override
    public void syncKqDakaBuGroupId(KqDakaLogQueryCriteria criteria) {
        Integer i = 0;//userDakaCount(criteria);
        if (UtilValidate.isEmpty(criteria.getAddDate())) {
            //获取昨天
            String s = DateKit.dateFormat(DateKit.getYesterday(), "yyyy-MM-dd");
            criteria.setAddDate(s);
        }
        if (UtilValidate.isEmpty(i) || i == 0) {
            List<KqDept> kqDepts = kqDeptService.queryAll(null);
            for (KqDept kqDept : kqDepts) {
                KqUserQueryCriteria c2 = new KqUserQueryCriteria();
                c2.setKqGroupId(kqDept.getId());//杨丽萍
                List<KqUser> kqUsers = kqUserService.queryAll(c2);

                for (int a = 0; a < kqUsers.size(); a++) {
                    KqUser kqUser = kqUsers.get(a);
                    JSONObject jsonObject2 = dingdingCheckService.getcolumnval(kqUser.getUserId(), "470928305,470928325", criteria.getAddDate() + " 00:00:00");
                    JSONObject ka_result_json = operatorColumnval(jsonObject2);

                    JSONObject jsonObject = dingdingCheckService.getupdatedata(kqUser.getUserId(), criteria.getAddDate());
                    operatorColumnval2(kqUser, jsonObject, ka_result_json);

//                    try {
//
//                    }catch (Exception e) {
//                        log.error("同步到day-log计算时间有误",e);
//                    }


                }

                syncKqDayLog(criteria, kqDept);
            }
        }
    }


    @Override
    public void syncKqDayLog(KqDakaLogQueryCriteria criteria, KqDept kqDept) {
//        if (UtilValidate.isEmpty(criteria.getAddDate())) {
//            //获取昨天
//            String s = DateKit.dateFormat(DateKit.getYesterday(), "yyyy-MM-dd");
//            criteria.setAddDate(s);
//        }

        KqDakaLogQueryCriteria c2 = new KqDakaLogQueryCriteria();
        c2.setGroupId(kqDept.getId());
        c2.setAddDate(criteria.getAddDate());
//            c2.setUserName("罗建华");
        List<KqDakaLog> kqDakaLogs = getByGroupId(c2);


        KqDayLog dayLog = oneByGroupId(c2);

        KqGroupRuleQueryCriteria c3 = new KqGroupRuleQueryCriteria();
        c3.setDeptId(kqDept.getId());
        List<ViewKqRule> ruleGroupList = kqGroupRuleService.getRuleGroupList(c3);

        if (UtilValidate.isEmpty(dayLog)) {


            for (KqDakaLog kqDakaLog : kqDakaLogs) {
                ViewKqDakaLog vDakaLog = new ViewKqDakaLog();
                BeanUtils.copyProperties(kqDakaLog, vDakaLog);
                vDakaLog.setGroupName(kqDept.getGroupName());
                ViewKqRule kqRule = null;
                KqDayLog kqDayLog = new KqDayLog();
                if (UtilValidate.isNotEmpty(kqDakaLog.getDdTimes())) {
                    String[] time_arr = kqDakaLog.getDdTimes().split(",");
                    //人员打卡日期记录
                    //匹配考勤规则
                    kqRule = getDakaRule(vDakaLog, time_arr, ruleGroupList);
                    operatorTime(vDakaLog, time_arr, kqRule);
                    kqDayLog.setXtQuantianShichang(vDakaLog.getXtQuantianShichang());
                    if (UtilValidate.isNotEmpty(vDakaLog.getJiaQingTxt())) {
                        kqDayLog.setXiuxiType(0);
                    }
                } else {
                    kqDayLog.setXtQuantianShichang(BigDecimal.ZERO);
                }
                if (UtilValidate.isEmpty(kqRule)) {
                    //查找正常班
                    //正常班
                    for (ViewKqRule kqRule2 : ruleGroupList) {
                        if (kqRule2.getType().equals(1)) {
                            kqRule = kqRule2;
                            break;
                        }
                    }
                }
                if (UtilValidate.isNotEmpty(kqRule)) {
                    kqDayLog.setKqRuleId(kqRule.getId());
                }
                kqDayLog.setDakaId(kqDakaLog.getId());
                String add_date = DateKit.dateFormat(kqDakaLog.getAddDate()).split(" ")[0];
                kqDayLog.setAddDate(kqDakaLog.getAddDate());
                kqDayLog.setAddDateStr(add_date);
                kqDayLog.setUserId(kqDakaLog.getUserId());
                kqDayLog.setUserName(kqDakaLog.getUserName());
                kqDayLogService.saveOrUpdate(kqDayLog);
            }
            if (!"dev".equals(PD_MATCH)) {
                dingNoticeService.kaWaitCheck(criteria.getAddDate(), kqDept, kqDakaLogs.size());
            }
        } else {
            //合并打卡数据
            List<KqDayLog> kqDayLogs = dayListByGroupId(c2);
            for (KqDayLog kqDayLog : kqDayLogs) {
                ViewKqRule kqRule = null;
                for (KqDakaLog kqDakaLog : kqDakaLogs) {
                    if (UtilValidate.isEmpty(kqDayLog.getDakaId()) &&
                            kqDakaLog.getUserId().equals(kqDayLog.getUserId())) {

                        ViewKqDakaLog vDakaLog = new ViewKqDakaLog();
                        BeanUtils.copyProperties(kqDakaLog, vDakaLog);
                        vDakaLog.setGroupName(kqDept.getGroupName());
                        if (UtilValidate.isNotEmpty(kqDakaLog.getDdTimes())) {
                            String[] time_arr = kqDakaLog.getDdTimes().split(",");
                            //人员打卡日期记录
                            //匹配考勤规则
                            kqRule = getDakaRule(vDakaLog, time_arr, ruleGroupList);
//                            operatorTime(vDakaLog, time_arr, kqRule);
//                            kqDayLog.setXtQuantianShichang(vDakaLog.getXtQuantianShichang());
//                            if(UtilValidate.isNotEmpty(vDakaLog.getJiaQingTxt())){
//                                kqDayLog.setXiuxiType(0);
//                            }
                        } else {
                            kqDayLog.setXtQuantianShichang(BigDecimal.ZERO);
                        }
                        if (UtilValidate.isEmpty(kqRule)) {
                            //查找正常班
                            //正常班
                            for (ViewKqRule kqRule2 : ruleGroupList) {
                                if (kqRule2.getType().equals(1)) {
                                    kqRule = kqRule2;
                                    break;
                                }
                            }
                        }
                        if (UtilValidate.isNotEmpty(kqRule)) {
                            kqDayLog.setKqRuleId(kqRule.getId());
                        }

                        kqDayLog.setDakaId(kqDayLog.getDakaId());
                        kqDayLogService.saveOrUpdate(kqDayLog);
                    }
                }
            }
        }


    }


    @Override
    public void syncAllDayLog(KqDakaLogQueryCriteria criteria) {
        List<KqDept> kqDepts = kqDeptService.queryAll(null);
        for (KqDept kqDept : kqDepts) {
            syncKqDayLog(criteria, kqDept);
        }
    }


    @Override
    public void syncAllInit() {
        String s = "2025-11-01,2025-11-02,2025-11-03,2025-11-04,2025-11-05,2025-11-06,2025-11-07,2025-11-08,2025-11-09,2025-11-10,2025-11-11,2025-11-12,2025-11-13";
        String[] split = s.split(",");
        for (String s1 : split) {
            KqDakaLogQueryCriteria c = new KqDakaLogQueryCriteria();
            c.setAddDate(s1);
            syncAllDayLog(c);
        }
    }

    /**
     * 钉钉打卡数据映射 22
     *
     * @param kqUser
     * @param jsonObject
     */
    public void operatorColumnval2(KqUser kqUser, JSONObject jsonObject, JSONObject ka_result_json) {
        // 470928326,470928305,470928307,470928327,470928329,470928331,470928333
        KqDakaLog kqDakaLog = null;
        try {
            kqDakaLog = new KqDakaLog();
            kqDakaLog.setUserId(kqUser.getUserId());
            kqDakaLog.setUserName(kqUser.getUserName());
            //kqDakaLog.setDdTxtJson(jsonObject.toJSONString());
            kqDakaLog.setXtShiJianJson(ka_result_json.toJSONString());
            JSONArray column_vals = jsonObject.getJSONArray("check_record_list");
            String addDate = jsonObject.getString("work_date");
            List<String> times = new ArrayList<String>();
            for (int a = 0; a < column_vals.size(); a++) {
                JSONObject column_val = column_vals.getJSONObject(a);
                String user_check_time = column_val.getString("user_check_time");
                times.add(user_check_time.split(" ")[1]);
            }
            //时间排序
            if (UtilValidate.isNotEmpty(times)) {
                sortTimeStrings(times);
                kqDakaLog.setDdTimes(String.join(",", times));
            }
            kqDakaLog.setAddDate(DateKit.dateFormat(addDate));
            kqDakaLog.setSubStatus(0);
            saveOrUpdate(kqDakaLog);


        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }


    }


    /**
     * 对时间字符串数组进行排序
     *
     * @param timeStrings 时间字符串数组，格式为HH:mm:ss
     */
    public void sortTimeStrings(List<String> timeStrings) {
        // 定义时间格式器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        timeStrings.sort(new Comparator<String>() {

            @Override
            public int compare(String time1, String time2) {
                // 解析时间字符串为LocalTime对象
                LocalTime t1 = LocalTime.parse(time1, formatter);
                LocalTime t2 = LocalTime.parse(time2, formatter);

                // 比较两个时间
                return t1.compareTo(t2);
            }
        });

    }


    @Override
    public void testGetDd() {
//        JSONObject getattcolumns = dingdingCheckService.getattcolumns();
//        System.out.println(getattcolumns);
        JSONObject jsonObject = dingdingCheckService.getcolumnval("255635201321531151", "470928305,470928325", "2025-10-20 00:00:00");
        operatorColumnval(jsonObject);
    }


    @Override
    public ApprovalCreateViewDto kqApprovalCreateView() {
        String userName = getUserName();
        KqDept kqDept = kqDeptService.findByGroupUserName(userName);
        SysApprovalSetting approvalSetting = sysApprovalSettingService.findByApprovalName("");
        String approvalSettingId = approvalSetting.getApprovalSettingId();
        SysApprovalSettingLine line = dbApprovalLogService.getMatchingApprovalLines(approvalSettingId, null, "");
        List<DbApprovalNode> nodes = new ArrayList<>();
        List<SysApprovalSettingNode> items = line.getItems();
        boolean is_first = false;//是否第一个审批人

        for (int i = 0; i < items.size(); i++) {
            SysApprovalSettingNode item = items.get(i);

            DbApprovalNode dbApprovalNode = new DbApprovalNode();

            dbApprovalNode.setUserId(item.getUserId());
            dbApprovalNode.setUserName(item.getUserName());

            if (UtilValidate.isNotEmpty(item.getIzMatcheManage()) && item.getIzMatcheManage().equals(1)) {//是否匹配上级领导

                if (item.getSort().equals(1) && UtilValidate.isNotEmpty(kqDept.getGroupUserId2())) {
                    dbApprovalNode.setUserId(kqDept.getGroupUserId2());
                    dbApprovalNode.setUserName(kqDept.getGroupUserName2());
                    dbApprovalNode.setApproverType(item.getApproverType());
                    dbApprovalNode.setApprovalSettingNodeId(item.getApprovalSettingNodeId());
                    dbApprovalNode.setSort(item.getSort());
                    dbApprovalNode.setStatus(0);
                    if (item.getApproverType() == 1 && !is_first) {
                        dbApprovalNode.setStatus(1);
                        is_first = true;
                    }
                    nodes.add(dbApprovalNode);
                }
                if (item.getSort().equals(2) && UtilValidate.isNotEmpty(kqDept.getManageUserId())) {
                    dbApprovalNode.setUserId(kqDept.getManageUserId());
                    dbApprovalNode.setUserName(kqDept.getManageUserName());

                    dbApprovalNode.setApproverType(item.getApproverType());
                    dbApprovalNode.setApprovalSettingNodeId(item.getApprovalSettingNodeId());
                    dbApprovalNode.setSort(item.getSort());
                    dbApprovalNode.setStatus(0);
                    if (item.getApproverType() == 1 && !is_first) {
                        dbApprovalNode.setStatus(1);
                        is_first = true;
                    }
                    nodes.add(dbApprovalNode);
                }

            } else {
                nodes.add(dbApprovalNode);
            }


        }
        ApprovalCreateViewDto dto = new ApprovalCreateViewDto();
        dto.setNodes(nodes);
        return dto;
    }


    /**
     * 钉钉打卡数据映射
     *
     * @param getcolumnval
     */
    public JSONObject operatorColumnval(JSONObject getcolumnval) {

        /**
         * 470928302 应出勤天数
         * 470928326 班次
         * 470928305 出勤天数
         * 470928307 工作时长
         * 470928325 考勤结果
         * 470928327 上班1打卡时间
         * 470928329 下班1打卡时间
         * 470928331 上班2打卡时间
         * 470928333 下班2打卡时间
         * 470928321 加班-审批单统计
         * 470928336 上班3打卡结果 470928335 上班3打卡时间   这个一般没数据
         * 470928338 下班3打卡结果 470928337 下班3打卡时间
         */
        // 470928326,470928305,470928307,470928327,470928329,470928331,470928333
        JSONObject jsonObject = new JSONObject();
        try {

            JSONArray column_vals = getcolumnval.getJSONArray("column_vals");
            String addDate = null;
            for (int a = 0; a < column_vals.size(); a++) {
                JSONObject column_val = column_vals.getJSONObject(a);
                String column_id = column_val.getJSONObject("column_vo").getString("id");
                JSONObject column_value_json = column_val.getJSONArray("column_vals").getJSONObject(0);
                if (addDate == null) {
                    addDate = column_value_json.getString("date");
                }
                jsonObject.put("addDate", addDate);
                //班次
//                if(column_id.equals("470928326")){
//                    kqDakaLog.setTimeRange(column_value_json.getString("value"));
//                }
                //
                //应出勤天数
//                if(column_id.equals("470928302")){
//                    jsonObject.put("应出勤天数",column_value_json.getBigDecimal("value"));
//                }
                //出勤天数
                if (column_id.equals("470928305")) {
                    jsonObject.put("出勤天数", column_value_json.getBigDecimal("value"));
                }
                //工作时长
                if (column_id.equals("470928307")) {
                    jsonObject.put("工作时长", column_value_json.getBigDecimal("value"));

                }
                // 考勤结果
                if (column_id.equals("470928325")) {
                    jsonObject.put("考勤结果", column_value_json.getString("value"));
                }

            }
            // System.out.println(jsonObject);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return jsonObject;

    }


    @Override
    public List<KqDakaLog> getByGroupId(KqDakaLogQueryCriteria criteria) {
        return baseMapper.getByGroupId(criteria);
    }


    @Override
    public KqDayLog oneByGroupId(KqDakaLogQueryCriteria criteria) {
        return baseMapper.oneByGroupId(criteria);
    }

    @Override
    public List<KqDayLog> dayListByGroupId(KqDakaLogQueryCriteria criteria) {
        return baseMapper.dayListByGroupId(criteria);
    }
}
